<template>
  <div
    id="request_by_dims_chart"
    class="echarts"
  ></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts'
import { onMounted, onUnmounted, ref, watch } from 'vue'

interface Props {
  metricsData: {
    vea_request_total_by_dims: Array<{
      labels: {
        method: string
        path: string
      }
      value: number
    }>
  } | null
}

const props = defineProps<Props>()

const chartDom = ref<HTMLElement | null>(null)
const myChart = ref<echarts.ECharts | null>(null)

interface RequestData {
  path: string
  method: string
  value: number
}

// 图表配置
const getChartOption = (data: RequestData[]) => {
  return {
    title: {
      text: '请求路径',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: function (params: { dataIndex: number; value: number; percent: number }) {
        // 在tooltip中显示完整信息
        const item = data[params.dataIndex]
        if (!item) return ''
        return `${item.method} ${item.path}<br/>请求数: ${params.value} (${params.percent}%)`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll',
      formatter: function (name: string) {
        if (!name) return ''
        // 图例中只显示路径的最后一部分
        const [method, path] = name.split(' ')
        if (!path) return name
        const shortPath = path.replace(/^\/api\/v1/, '') || path
        return `${method} ${shortPath}`
      }
    },
    series: [
      {
        name: '请求分布',
        type: 'pie',
        radius: '50%',
        center: ['65%', '50%'], // 将图形向右移动
        data: data.map(item => ({
          name: `${item.method} ${item.path.replace(/^\/api\/v1/, '') || item.path}`,
          value: item.value
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
}

// 更新数据
const updateData = () => {
  if (!props.metricsData) return

  const requestData: RequestData[] = props.metricsData.vea_request_total_by_dims.map(item => ({
    path: item.labels.path,
    method: item.labels.method,
    value: item.value
  }))
  myChart.value?.setOption(getChartOption(requestData))
}

// 监听数据变化
watch(() => props.metricsData, () => {
  updateData()
}, { deep: true })

// 初始化图表
const initChart = () => {
  if (!chartDom.value) return

  myChart.value = echarts.init(chartDom.value)
  myChart.value.setOption(getChartOption([]))

  // 添加窗口大小变化的监听
  window.addEventListener('resize', () => {
    myChart.value?.resize()
  })
}

onMounted(() => {
  chartDom.value = document.getElementById('request_by_dims_chart')
  initChart()
  if (props.metricsData) {
    updateData()
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', () => {
    myChart.value?.resize()
  })
  myChart.value?.dispose()
})
</script>

<style scoped>
.echarts {
  width: 100%;
  height: 320px;
}
</style>